class_name LogicalEffectComponent
extends BaseComponent

#region 属性
var logicalEffects:Array[LogicalEffectBase] = []
#endregion
#region 字段
#endregion
#region 信号
#endregion

#region 基类方法
func init_component(entity):
	super.init_component(entity)
	for child in get_children():
		if child is LogicalEffectBase:
			child.init_effect(self)
			logicalEffects.append(child)
			if child.can_trigger():
				_apply_effect(child)
#endregion
#region 公共方法
func clear_all_effect():
	for effect in logicalEffects:
		_refresh_effect(effect)
#endregion
#region 私有方法
func _apply_effect(effect:LogicalEffectBase):
	if not effect.active_state:
		effect.apply()
		if not effect.get_life_state():
			_on_effect_complete()
			_complete_effect(effect)
func _remove_effect(effect:LogicalEffectBase):
	if effect.active_state:
		effect.remove()
		logicalEffects.erase(effect)
		for other_effect in logicalEffects:
			_refresh_effect(other_effect)
func _update_effect(effect:LogicalEffectBase):
	if not effect.active_state:
		return
	if effect.get_life_state():
		effect.update()
	else :
		_on_effect_complete()
		_complete_effect(effect)
func _refresh_effect(effect:LogicalEffectBase):
	if effect.active_state:
		effect.refresh()
func _complete_effect(effect:LogicalEffectBase):
	if effect.active_state:
		effect.complete()
		logicalEffects.erase(effect)
func _on_effect_complete():
	for other_effect in logicalEffects:
		if not other_effect.active_state and not other_effect.is_completed and other_effect.can_trigger():
			_apply_effect(other_effect)
#endregion
#region 生命周期函数
func _init() -> void:
	# Component名称
	component_name = "LogicalEffectComponent"
	priority = 5
func _process(delta: float) -> void:
	if not inited:
		return
	for effect in logicalEffects:
		_update_effect(effect)
func _exit_tree() -> void:
	call_deferred("clear_all_effect")
#endregion


